#include <iostream>
using std::cout;
using std::endl;

class Singleton{
    friend class AutoRelease;
public:
    static Singleton* getInstance(){
        if(nullptr == _pInstance){
            _pInstance = new Singleton();
            cout << "Singleton created at: " << _pInstance << endl;
        }
        return _pInstance;
    }

    // 添加临时公有方法（仅用于调试）
    static Singleton** getInstancePointerAddress() {
        return &_pInstance;  // 返回指针变量本身的地址
    }

private:
    Singleton() {
        cout << "Singleton() @" << this << endl; 
    }
    ~Singleton() { 
        cout << "_pInstance variable address: " << Singleton::getInstancePointerAddress() << endl;
        cout << "_pInstance points to: " << *Singleton::getInstancePointerAddress() << endl;
        cout << "~Singleton() @" << this << endl; 
    }
    static Singleton* _pInstance;
};
Singleton* Singleton::_pInstance = nullptr;

class AutoRelease {
public:
    AutoRelease(Singleton* s) : _s(s) {
        cout << "AutoRelease() @" << this 
             << " holding Singleton @" << _s << endl;
    }

    ~AutoRelease(){
        cout << "~AutoRelease() @" << this 
             << " deleting Singleton @" << _s << endl;
        if(_s){
            delete _s;
            _s = nullptr;
        }
    }
    // 临时添加（仅用于调试）
    Singleton** getSPointerAddress() { return &_s; }  // 获取_s自身的地址
    Singleton* getPointer() { return _s; }            // 获取_s指向的地址

private:
    Singleton* _s;
};

void test(){
    cout << "\n----- Enter test() -----" << endl;
    
    AutoRelease ar(Singleton::getInstance());
    cout << "ar address: " << &ar << ", ar._s: " << ar.getSPointerAddress() << ", ar._s point to " << ar.getPointer() << endl;
    
    AutoRelease ar2(Singleton::getInstance());
    cout << "ar2 address: " << &ar2 << ", ar2._s: " << ar2.getSPointerAddress() << ", ar2._s point to " << ar2.getPointer() << endl;
    
    cout << "----- Leaving test() -----" << endl;
}

int main() {
    cout << "----- Program Start -----" << endl;
    Singleton* p = Singleton::getInstance();
//    cout << "_pInstance variable address:" << &p << endl;   // 这返回的是局部变量p的地址,emm...
//    cout << "_pInstance points to:" << p << endl;
   
    cout << "_pInstance variable address: " << Singleton::getInstancePointerAddress() << endl;
    cout << "_pInstance points to: " << *Singleton::getInstancePointerAddress() << endl;

    test();
    
    cout << "\n----- Program End -----" << endl;
    return 0;
}
